class WebSocketClient {
    constructor() {
        this.stompClient = null;
        this.subscriptions = new Map();
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.activeClose = false;
    }

    init(params) {
        const socket = new SockJS(params.url);
        this.stompClient = StompJs.Stomp.over(socket);
        // 配置心跳
        this.stompClient.heartbeat.outgoing = 10000;
        this.stompClient.heartbeat.incoming = 0;

        // 连接处理
        this.stompClient.connect(
            {},
            (frame) => this.handleConnect(frame, params),
            (error) => this.handleError(error, params)
        );
    }

    handleConnect(frame, params) {
        this.reconnectAttempts = 0;
        console.log('Connected to STOMP');

        // 默认订阅
        if (params.subscriptions) {
            params.subscriptions.forEach(sub => {
                this.addSubscription(sub.topic, sub.callback);
            });
        }

        // 触发用户自定义的 onopen
        params.onopen?.(frame);
    }
    sendMessage(){
        this.stompClient.send("/app/hello", {topic:"greetings", type:"user"}, JSON.stringify({ message:"Hello, WebSocket!"}));
    }
    handleError(error, params) {
        console.error('STOMP Error:', error);
        if (!this.activeClose && this.reconnectAttempts < this.maxReconnectAttempts) {
            setTimeout(() => {
                this.reconnectAttempts++;
                this.init(params);
            }, 5000);
        }
    }

    addSubscription(topic, callback) {
        const sub = this.stompClient.subscribe(topic, (message) => {
            callback(JSON.parse(message.body));
        });
        this.subscriptions.set(topic, sub);
    }

    close() {
        this.activeClose = true;
        this.subscriptions.forEach(sub => sub.unsubscribe());
        this.stompClient.disconnect();
    }
}
